package com.example.admin.testdemo.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;

import com.example.admin.testdemo.R;
import com.example.admin.testdemo.adapter.MonitorListAdapter;
import com.example.admin.testdemo.dao.ResultDao;
import com.example.admin.testdemo.dao.TempData;
import com.example.admin.testdemo.enty.Result;
import com.example.admin.testdemo.helper.LogUtil;
import com.example.admin.testdemo.rs232.Command;
import com.example.admin.testdemo.rs232.Serial;
import com.example.admin.testdemo.util.DateTimeUtil;
import com.example.admin.testdemo.util.ScreenUtil;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThjOldActivity extends BaseActivity implements AdapterView.OnItemClickListener, View.OnClickListener {
    private static String TAG = "ThjOldActivity";
    private GridView gv;
    private Serial serial;
    private MonitorListAdapter adapter;
    private int delay = 5;
    private int sendFlag = 0;
    private int recivceFlag = 0;
    private EditText et_cs;
    private EditText et_hds;
    private EditText et_send;
    private EditText et_recive;
    private EditText et_monitor;
    private EditText et_address;
    private EditText et_recive_485;
    private EditText et_send_485;
    private Button btn_save;
    private Button btn_hand;
    private Button btn_start;
    private Button btn_check;
    private Button btn_485;
    private Button btn_dj;
    private Button btn_saveResult;
    private EditText et_hand;
    private EditText et_check;
    private EditText et_yy;
    private EditText et_result;
    private EditText et_dj;
    private EditText et_recive_dj;
    private EditText et_send_dj;
    private int x = 1;
    private int add = 1;
    private int layer = 0;
    private int row = 0;
    private int singleFlag = 0;
    boolean btnSave = false;
    boolean btnCheck = false;
    private boolean isCheck = false;
    private boolean isSave = false;
    private boolean isHand = false;
    private boolean isSingleDegug = false;
    private ScheduledExecutorService scheduledThreadPool;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int width = ScreenUtil.getScreenWidth(this);
//        if (width == 1080) {
        setContentView(R.layout.activity_thj_old);
//        }
//        Log.e(TAG,"width="+width);
        initView();
        initData();

    }


    private Serial.DataCallback callback = new Serial.DataCallback() {
        @Override
        public void onDataReceived(byte[] buffer, int size) {
            Log.e(TAG, "接收：" + Command.printByteInfo(buffer));
            singleDebug(buffer);
            handhandshae(buffer);
            handcheck(buffer);
            handleConnect(buffer);
            handMonitor(buffer);
            handMonitorResult(buffer);

        }
    };

    private void handleConnect(byte[] buffer) {
        if (isBtn485 && buffer[0] == (byte) 0xAA && buffer[2] == (byte) 0xF3) {
            recivceFlag++;
            setEt(et_recive_485, recivceFlag);
        }
    }

    private void handMonitorResult(byte[] buffer) {
        if (isBtnDj && buffer[0] == (byte) 0xAA && buffer[2] == (byte) 0xF4 && buffer[3] == (byte) 0x4F) {
            recivceFlag++;
            setEt(et_recive_dj, recivceFlag);
        }
    }

    private void singleDebug(byte[] buffer) {
        if (isSingleDegug && buffer[0] == (byte) 0xAA && buffer[2] == (byte) 0xF5 && buffer[5] == (byte) 0x30) {
            isSingleDegug = false;
            setEt(et_result, "转动正常");
            setEt(et_yy, "正常");
        } else if (isSingleDegug && buffer[0] == (byte) 0xAA && buffer[2] == (byte) 0xF5 && buffer[5] == (byte) 0x31) {
            setEt(et_result, "正在转动");
        } else if (isSingleDegug && buffer[0] == (byte) 0xAA && buffer[2] == (byte) 0xF5 && buffer[4] == (byte) 0x47) {
            isSingleDegug = false;
            setEt(et_result, "转动异常");
            handReason(buffer[5]);
        }
    }

    private void handReason(byte b) {
        if (b == (byte) 0xD2) {
            setEt(et_yy, "电机微动开关异常或反馈线异常");
        } else {
            setEt(et_yy, "未知错误");
        }
    }

    private void handMonitor(byte[] buffer) {

        if (isSave && buffer[0] == (byte) 0xAA && buffer[2] == (byte) 0xF4 && buffer[3] == (byte) 0x4F) {
            isQuery = true;
        } else if (isSave && buffer[0] == (byte) 0xAA && buffer[2] == (byte) 0xF5 && buffer[4] == (byte) 0x47) {
            isQuery = false;
        } else if (isSave && buffer[0] == (byte) 0xAA && buffer[2] == (byte) 0xF5 && buffer[5] == (byte) 0x30) {
            recivceFlag++;
            setEt(et_recive, recivceFlag);
            isQuery = false;
        }

    }

    private void handhandshae(byte[] buffer) {
        if (isHand) {
            setEt(et_hand, Command.printChar(buffer));
            isHand = false;
        }
    }

    private void handCheckConnect(byte[] buffer) {
        if (isBtn485) {

        }
    }

    private void handcheck(byte[] buffer) {
        if (isCheck && buffer[0] == (byte) 0xAA && buffer[4] == (byte) 0x32) {
            setEt(et_check, "未检测到商品");
        } else if (isCheck && buffer[0] == (byte) 0xAA && buffer[4] == (byte) 0x31) {
            setEt(et_check, "检测到商品");
        }
    }


    private void initData() {
        serial = Serial.getSerialInstance();
        serial.setCallback(callback);
        startTimer();

    }

    private boolean isQuery = false;

    private void startTimer() {
        if (scheduledThreadPool == null) {
            scheduledThreadPool = new ScheduledThreadPoolExecutor(1);
        }
        scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (isSave) {
                    loopTest();
                }


            }
        }, 0, delay, TimeUnit.SECONDS);
        scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (isQuery) {
                    checkMoniterResult();
                }


            }
        }, 0, 1, TimeUnit.SECONDS);

        scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (isCheck) {
                    loopCheck();
                } else if (isSingleDegug) {
                    serial.sendData(Command.engineResult(1));
                }
            }
        }, 0, 1, TimeUnit.SECONDS);
        scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (isBtn485) {
//                    serial.sendData(Command.outGoods(1,1,1));
//                    delay(4000);
                    sendConnect();
                }
            }
        }, 0, 500, TimeUnit.MILLISECONDS);

        scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (isBtnDj) {
                    sendCommandDj(add, layer, row);
                }
            }
        }, 0, 5000, TimeUnit.MILLISECONDS);
    }

    private void delay(long time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void sendConnect() {
        if (serial != null) {
            sendFlag++;
            setEt(et_send_485, sendFlag);
            serial.sendData(Command.outGoodsResult());
        }
    }

    private void checkMoniterResult() {
        serial.sendData(Command.engineResult(1));
    }


    private void loopCheck() {
        if (serial != null) {
            serial.sendData(Command.outGoodsResult());
        }
    }

    int flag = 1;

    private void loopTest() {
        int layer = Integer.parseInt(et_cs.getText().toString());
        int hd = Integer.parseInt(et_hds.getText().toString());
        int r = getLayer(flag, hd);
        sendCommand(1, x, r);
        setEt(et_monitor, x + "-" + r);
        if (r == hd) {
            x++;
            if (x > layer) {
                x = 1;
            }
        }
        if (flag > 65535) {
            flag = 0;
        }
        flag++;
    }

    private int getLayer(int flag, int hd) {
        int temp = flag % hd;
        if (temp == 0) {
            temp = hd;
        }
        return temp;
    }


    private void initView() {
        gv = findViewById(R.id.gv);
        gv.setOnItemClickListener(this);
        adapter = new MonitorListAdapter(ThjOldActivity.this, TempData.getMonitors(6, 10));
        gv.setAdapter(adapter);
        btn_save = findViewById(R.id.btn_save);
        btn_save.setOnClickListener(this);
        btn_check = findViewById(R.id.btn_check);
        btn_check.setOnClickListener(this);
        btn_hand = findViewById(R.id.btn_hand);
        btn_hand.setOnClickListener(this);
        btn_saveResult = findViewById(R.id.btn_saveResult);
        btn_saveResult.setOnClickListener(this);
        btn_start = findViewById(R.id.btn_start);
        btn_start.setOnClickListener(this);
        btn_485 = findViewById(R.id.btn_485);
        btn_485.setOnClickListener(this);
        btn_dj = findViewById(R.id.btn_dj);
        btn_dj.setOnClickListener(this);
        et_cs = findViewById(R.id.et_cs);
        et_hds = findViewById(R.id.et_hds);
        et_recive = findViewById(R.id.et_recive);
        et_send = findViewById(R.id.et_send);
        et_monitor = findViewById(R.id.et_monitor);
        et_hand = findViewById(R.id.tv_hand);
        et_recive_485 = findViewById(R.id.et_recive_485);
        et_send_485 = findViewById(R.id.et_send_485);
        et_address = findViewById(R.id.et_address);
        et_result = findViewById(R.id.et_result);
        et_yy = findViewById(R.id.et_yy);
        et_recive_dj = findViewById(R.id.et_recive_dj);
        et_send_dj = findViewById(R.id.et_send_dj);
        et_dj = findViewById(R.id.et_dj);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String temp = adapter.getItem(position);
        String[] tt = temp.split("-");
        isSingleDegug = true;
        singleFlag = 0;
        setEt(et_result, "");
        setEt(et_yy, "");
        sendCommand(1, Integer.parseInt(tt[0]), Integer.parseInt(tt[1]));
    }

    private void sendCommand(int add, int x, int y) {
        if (serial != null) {
            byte[] command = Command.outGoods(add, x, y);
            serial.sendData(command);
            if (isSave) {
                sendFlag++;
                setEt(et_send, sendFlag);
            }
            layer = x;
        }
    }

    private void sendCommandDj(int add, int x, int y) {
        if (serial != null) {
            byte[] command = Command.outGoods(add, x, y);
            serial.sendData(command);
            Log.e(TAG, "发送指令：" + Command.printByteInfo(command));
            sendFlag++;
            setEt(et_send_dj, sendFlag);
        }
    }

    private boolean isBtn485 = false;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_save:
                clicktest();
                break;
            case R.id.btn_hand:
                hands();
                break;
            case R.id.btn_check:
                check();
                break;
            case R.id.btn_start:
                break;
            case R.id.btn_saveResult:
                saveResult();
                break;
            case R.id.btn_485:
                saveResult485();
                break;
            case R.id.btn_dj:
                saveResultDj();
                break;
        }
    }

    private boolean isBtnDj = false;

    private void saveResultDj() {
        String temp = et_dj.getText().toString();
        String[] arrTemp = temp.split("-");
        add = Integer.parseInt(arrTemp[0]);
        layer = Integer.parseInt(arrTemp[1]);
        row = Integer.parseInt(arrTemp[2]);
        if (!isBtnDj) {
            sendFlag = 0;
            recivceFlag = 0;
            et_recive_dj.setText("0");
            et_send_dj.setText("0");
            btn_dj.setText("测试中");
            isBtnDj = true;
        } else {
            btn_dj.setText("开始");
            isBtnDj = false;
        }
    }

    private void saveResult485() {
        if (!isBtn485) {
            com.example.admin.testdemo.util.LogUtil.e(TAG, "start---------------");
            sendFlag = 0;
            recivceFlag = 0;
            et_send_485.setText("0");
            et_recive_485.setText("0");
            btn_485.setText("测试中");
            isBtn485 = true;
        } else {
            com.example.admin.testdemo.util.LogUtil.e(TAG, "发送次数：" + et_send_485.getText().toString() +
                    "接收次数：" + et_recive_485.getText().toString());
            com.example.admin.testdemo.util.LogUtil.e(TAG, "end---------------");
            btn_485.setText("开始");
            isBtn485 = false;
        }
    }


    private void saveResult() {
        ResultDao resultDao = ResultDao.getResultDaoInstance(this);
        Result result = resultDao.getResultByName("qindaji");
        String send = et_send.getText().toString();
        String recive = et_recive.getText().toString();
        result.setRecive(Integer.parseInt(recive));
        result.setSend(Integer.parseInt(send));
        result.setEndTime(DateTimeUtil.getSysTimeYMDHMS());
        int temp = resultDao.add(result);
        if (temp == 0) {
            setToast("保存成功");
        } else {
            setToast("保存失败");
        }
    }

    private void check() {
        isHand = false;
        isSave = false;
        isQuery = false;
        btn_save.setText("停止");
        if (btnCheck) {
            btn_check.setText("检测中");
            btnCheck = false;
            isCheck = true;
        } else {
            btn_check.setText("检测");
            btnCheck = true;
            isCheck = false;
        }
    }


    private void hands() {
        isHand = true;
        et_hand.setText("");
        isSave = false;
        btn_save.setText("开始");
        isCheck = false;
        btn_check.setText("检测");
        int add = getEtNum(et_address);
        if (serial != null) {
            serial.sendData(Command.handshake(add));
        }

    }

    private void engineResult() {
        if (serial != null) {
            serial.sendData(Command.engineResult(1));
        }

    }

    private void clicktest() {
        isCheck = false;
        btn_check.setText("检测");
        if (btnSave) {
            btn_save.setText("测试中");
            initEt();
            x = 1;
            recivceFlag = 0;
            sendFlag = 0;
            flag = 1;
            btnSave = false;
            isSave = true;
            isQuery = true;
        } else {
            btn_save.setText("开始");
            btnSave = true;
            isSave = false;
            isQuery = false;
        }
    }

    private void initEt() {
        et_recive.setText("0");
        et_send.setText("0");
    }


    private void setEt(final EditText et, final String flag) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                et.setText(flag);
            }
        });
    }

    private void setEt(final EditText et, final int flag) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                et.setText(Integer.toString(flag));
            }
        });
    }

    private void setBtn(final Button et, final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                et.setText(msg);
            }
        });
    }

    private int getEtNum(EditText et) {
        int tt = 1;
        String temp = et.getText().toString();
        if (!TextUtils.isEmpty(temp)) {
            tt = Integer.parseInt(temp);
        }
        return tt;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTimer();
    }

    private void stopTimer() {
        if (scheduledThreadPool != null) {
            scheduledThreadPool.shutdown();
        }
    }


}
